package com.ssyt.hiring.common.service;

import java.util.UUID;

import com.ssyt.hiring.common.Constants;
import com.ssyt.hiring.common.util.DBUtil;
import com.ssyt.hiring.common.util.EmailUtil;
import com.ssyt.hiring.company.entity.CompanyEntity;
import com.ssyt.hiring.talent.entity.TalentEntity;

public class ForgetPwdService {

	/**
	 * 判断邮箱地址是否存在
	 * 
	 * @param userType
	 * @param email
	 * @return true 存在、false 不存在
	 */
	public boolean isExistEmail(String userType, String email) {
		boolean result = false;
		if (Constants.HIRING_TALENT.equals(userType)) {
			TalentEntity talentEntity = DBUtil.getUniqueResult(
					TalentEntity.class, "SELECT * FROM talent WHERE email=?",
					email);
			if (talentEntity != null) {
				result = true;
			}
		} else if (Constants.HIRING_COMPANY.equals(userType)) {
			CompanyEntity companyEntity = DBUtil.getUniqueResult(
					CompanyEntity.class,
					"SELECT id FROM company WHERE email=?", email);
			if (companyEntity != null) {
				result = true;
			}
		} else {
			throw new RuntimeException("不存在的用户类型：" + userType);
		}
		return result;
	}

	/**
	 * 发送修改密码地址的邮件
	 * 
	 * @param email
	 * @param userType
	 * @return
	 */
	public boolean sendEmail(String email, String userType) {
		// 生成全球唯一标识码
		String securityKey = UUID.randomUUID().toString();
		// 发送邮件
		StringBuffer sb = new StringBuffer();
		sb.append("<p>你好 <a href=\"mailto:" + email + "\" target=\"_blank\">"
				+ email + "</a>!</p>");
		sb.append("<p>您已经请求了重置密码，您可以</p>");
		sb.append("<p><a href=\"http://localhost:8080/hiring/ForgetPwdServlet?command=toUpdatePasswordUI&email="
				+ email
				+ "&userType="
				+ userType
				+ "&securityKey="
				+ securityKey
				+ "\" target=\"_blank\">点此链接重置密码（此链接5分钟内有效）</a></p>");
		sb.append("<p>如果你没有请求重置密码，请忽略这封邮件</p>");
		sb.append("<p>在你点击上面链接修改密码之前，你的密码将会保持不变。</p>");
		boolean sendResult = EmailUtil.sendEmail(email, "Hiring重置密码信息",
				sb.toString());

		if (sendResult) {
			// 如果邮件发送成功，更新此次邮件的重置密码地址的过期时间
			long millis = System.currentTimeMillis() + (5 * 60 * 1000);
			if (Constants.HIRING_TALENT.equals(userType)) {
				DBUtil.executeUpdate(
						"UPDATE talent SET email_link_out_date=?, security_key=? WHERE email=?",
						millis, securityKey, email);
			} else if (Constants.HIRING_COMPANY.equals(userType)) {
				DBUtil.executeUpdate(
						"UPDATE company SET email_link_out_date=?, security_key=? WHERE email=?",
						millis, securityKey, email);
			} else {
				throw new RuntimeException("不存在的用户类型：" + userType);
			}

		}

		return sendResult;
	}

	/**
	 * 判断用户请求的修改密码地址是否已过期
	 * 
	 * @param userType
	 * @param email
	 * @return true为没过期
	 */
	public boolean isEmailLinkExpired(String userType, String email) {
		boolean result = false;
		if (Constants.HIRING_TALENT.equals(userType)) {
			TalentEntity talent = DBUtil.getUniqueResult(TalentEntity.class,
					"SELECT email_link_out_date FROM talent WHERE email=?",
					email);
			if (talent != null
					&& talent.getEmailLinkOutDate() > System
							.currentTimeMillis()) {
				result = true;
			}
		} else if (Constants.HIRING_COMPANY.equals(userType)) {
			CompanyEntity companyEntity = DBUtil.getUniqueResult(
					CompanyEntity.class,
					"SELECT email_link_out_date FROM company WHERE email=?",
					email);
			if (companyEntity != null
					&& companyEntity.getEmailLinkOutDate() > System
							.currentTimeMillis()) {
				result = true;
			}
		} else {
			throw new RuntimeException("不存在的用户类型：" + userType);
		}
		return result;
	}

	/**
	 * 判断邮箱和密钥是否匹配
	 * 
	 * @param userType
	 * @param email
	 * @param securityKey
	 * @return 如果为true 则匹配
	 */
	public boolean isMatched(String userType, String email, String securityKey) {
		boolean result = false;
		if (Constants.HIRING_TALENT.equals(userType)) {
			TalentEntity talent = DBUtil.getUniqueResult(TalentEntity.class,
					"SELECT * FROM talent WHERE email=? AND security_key=?",
					email, securityKey);
			if (talent != null) {
				result = true;
			}
		} else if (Constants.HIRING_COMPANY.equals(userType)) {
			CompanyEntity companyEntity = DBUtil.getUniqueResult(
					CompanyEntity.class,
					"SELECT * FROM talent WHERE email=? AND security_key=?",
					email, securityKey);
			if (companyEntity != null) {
				result = true;
			}

		} else {
			throw new RuntimeException("不存在的用户类型：" + userType);
		}
		return result;
	}

	/**
	 * 修改密码
	 * 
	 * @param userType
	 * @param email
	 * @param password
	 * @return
	 */
	public String updatePassword(String userType, String email, String password) {
		String result = "";
		if (Constants.HIRING_TALENT.equals(userType)) {
			int row = DBUtil.executeUpdate(
					"UPDATE talent SET password=? WHERE email=?", password,
					email);
			if (row > 0) {
				result = "talent";
			}
		} else if (Constants.HIRING_COMPANY.equals(userType)) {
			int row = DBUtil.executeUpdate(
					"UPDATE company SET password=? WHERE email=?", password,
					email);
			if (row > 0) {
				result = "company";
			}

		} else {
			throw new RuntimeException("不存在的用户类型：" + userType);
		}
		return result;
	}
}
